<?php
namespace App\Http\Controllers\Business\App\Statistic;

use App\Models\UserLogin;
use App\Models\User;

class StatisticManagement
{

    //在首页位置的时候写入数据，这里可能没有userId,判断用户的IP和user_agent，在买单页的位置写入数据，在充值的时候写入数据
    public static function addUserLoginAfterInfo($userId,$type,$userAgent,$Ip,$registerSource ='',$deviceId='',$osVersion ='',$phoneType=''){
        if($type == NULL){
            return ['status'=>'failed', 'message'=>'数据来源错误'];
        }
        if($Ip == NULL || empty($Ip)){
            return ['status'=>'failed', 'message'=>'IP不能为空'];
        }
        if($type == 'index'){
            //判断是否是同一天
            $startTime = date('Y-m-d',time()).' 00:00:00';
            $lastTime = date('Y-m-d',time()).' 23:59:59';
            $userLoginInfo = UserLogin::where('type',$type)->where('useragent',$userAgent)->where('ip',$Ip)
                ->where('created_at', '>=', $startTime)->where('created_at', '<=', $lastTime)->get()->count();
            if($userLoginInfo < 1){
                $userLogin = UserLogin::create([
                    'type'=>$type,
                    'useragent'=>$userAgent,
                    'ip'=>$Ip,
                    'registersource' => $registerSource,
                    'deviceid' => $deviceId,
                    'osversion' => $osVersion,
                    'phonetype' => $phoneType
                ]);
                $userLogin->save();
                return ['status'=>'success', 'message'=>'添加成功'];
            }else{
                return ['status'=>'failed', 'message'=>'该用户数据已经存在'];
            }
        }elseif(in_array($type,array('order','recharge'))){
            //判断userId是否存在和正确
            if($userId == NULL || empty($uerId)){
                if(!is_numeric($userId)){
                    return ['status'=>'failed', 'message'=>'传入数字类型错误'];
                }
                $userLogin = UserLogin::create([
                    'type'=>$type,
                    'useragent'=>$userAgent,
                    'userid'=>$userId,
                    'logintime'=>date('Y-m-d H:i:s',time()),
                    'ip'=>$Ip,
                    'registersource' => $registerSource,
                    'deviceid' => $deviceId,
                    'osversion' => $osVersion,
                    'phonetype' => $phoneType
                ]);
                $userLogin->save();
                return ['status'=>'success', 'message'=>'添加成功'];
            }else{
                return ['status'=>'failed', 'message'=>'该用户不存在'];
            }
        }else{
            return ['status'=>'failed', 'message'=>'参数错误'];
        }
    }
}